<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24
 * Time: 9:43
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use other\Tree;
use other\Wechat;
use think\Db;
use think\Loader;
use think\Request;

class Article extends AdminBase
{
    /**
     * 文章列表
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $chk = check_juri(request()->controller(), 'index', $this->_juri);
        if ($chk['status'])
        {
            $where = 'a.del_status = 0';
            $data['title']  = '';
            $data['cid']    = 0;
            $data['status'] = 'all';
            $date_start     = time();
            $date_end       = $date_start;
            if (Request::instance()->isGet())
            {
                $request = Request::instance()->param();
                if ($request)
                {
                    $data = $request;
                    if (isset($data['title']) && !empty($data['title']))
                    {
                        $where .= ' and CONCAT_WS(",", a.title, a.author, a.keywords, a.description) like "%'.$data['title'].'%"';
                    } else {
                        $data['title']  = '';
                    }

                    if (isset($data['cid']) && !empty($data['cid']))
                    {
                        $where .= ' and a.category_id = '.$data['cid'];
                    } else {
                        $data['cid']    = 0;
                    }

                    if (isset($data['status']) && $data['status'] != 'all')
                    {
                        $where .= ' and a.status = '.$data['status'];
                    } else {
                        $data['status'] = 'all';
                    }

                    /*if (isset($data['attr']) && !in_array(0, $data['attr']))
                    {
                        foreach ($data['attr'] as $k => $val) {
                            if ($k == 0)
                            {
                                $where .= ' and (a.attr FIND_IN_SET ('.$val.', attr)';
                            } else {
                                $where .= ' or a.attr FIND_IN_SET ('.$val.', attr)';
                            }
                            $where .= ')';
                        }
                    }*/
                    if (isset($data['daterange']) && !empty($data['daterange']))
                    {
                        $date_arr   = explode('-', $data['daterange']);
                        $date_start = strtotime(trim($date_arr[0]));
                        $date_end   = strtotime(trim($date_arr[1]));
                        if (($date_end-$date_start) > 0)
                        {
                            $where .= ' and a.create_time between '.$date_start.' and '.$date_end;
                        }
                    }
                }
            }
            $total = Loader::model('Article')
                ->alias('a')
                ->where($where)
                ->count();
            $list = Loader::model('Article')
                ->alias('a')
                ->field('a.id, a.thumb, a.title, a.other_title, a.category_id, a.author, a.hits, a.attr, a.is_top, a.create_time, a.update_time, a.status, a.url_post, c.title as category_name')
                ->join('__CATEGORY__ c', 'a.category_id = c.id', 'LEFT')
                ->where($where)
                ->order('a.sort desc, a.create_time desc')
                ->paginate(30, $total, ['query'=>['title'=>$data['title'], 'cid'=>$data['cid'], 'status'=>$data['status'], 'daterange'=>date('Y/m/d', $date_start).' - '.date('Y/m/d', $date_end)]]);
            $pages = $list->render();
            $cate = Db::name('category')
                ->field('id, title, parentid, attr')
                ->order('sort desc, create_time desc')
                ->select();
            $tree = new Tree($cate);
            $cate = $tree->get_tree(0);
            return view('index', [
                'list'      =>$list,
                'cate'      =>$cate,
                'pages'     =>$pages,
                'data'      =>$data,
                'date_start'=>$date_start,
                'date_end'  =>$date_end
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    /**
     * 添加文章
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $chk = check_juri(request()->controller(), 'add', $this->_juri);
        if ($chk['status'])
        {
            $list = Db::name('category')
                ->field('id, title, parentid, attr')
                ->order('sort desc, create_time desc')
                ->select();
            $tree = new Tree($list);
            $list = $tree->get_tree(0);
            return view('add', [
                'list'=>$list
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    /**
     * 执行添加文章
     * @return bool
     */
    public function doAdd()
    {
        if (request()->isPost())
        {
            $data   = Request::instance()->post();
            $result = $this->validate($data, 'Article');
            if ($result !== true)
            {
                return ['status'=>false, 'msg'=>$result];
            }
            $info   = img_upload_one('thumb');
            if ($info)
            {
                if ($info['status'])
                {
                    $data['thumb'] = $info['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info['msg']];
                }
            } else {
                $data['thumb'] = null;
            }
            $info2   = muti_img_upload('photos');
            if ($info2)
            {
                if ($info2['status'])
                {
                    $data['photos'] = $info2['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info2['msg']];
                }
            } else {
                $data['photos'] = null;
            }
            $info3   = muti_soft_upload('enclosure');
            if ($info3)
            {
                if ($info3['status'])
                {
                    $data['enclosure'] = $info3['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info3['msg']];
                }
            } else {
                $data['enclosure'] = null;
            }
            $system = Loader::model('Article');
            $system->add($data);
            return ['status'=>true, 'msg'=>$data];
        }
    }

    /**
     * 文章修改
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $chk = check_juri(request()->controller(), 'edit', $this->_juri);
        if ($chk['status'])
        {
            $id   = intval(input('param.id'));
            $info = Loader::model('Article')->get($id);
            $info = $info->toArray();
            $list = Db::name('category')
                ->field('id, title, parentid, attr')
                ->order('sort desc, create_time desc')
                ->select();
            $tree = new Tree($list);
            $list = $tree->get_tree(0);
            return view('edit', [
                'list'=>$list,
                'info'=>$info
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    /**
     * 执行文章修改
     * @return bool|string
     */
    public function doEdit()
    {
        if (request()->isPost())
        {
            $data         = Request::instance()->post();
            $data['attr'] = input('param.attr/a');
            $articleInfo  = Loader::model('Article')->get($data['id']);
            $result = $this->validate($data, 'Article');
            if ($result !== true)
            {
                return ['status'=>false, 'msg'=>$result];
            }
            $info   = img_upload_one('thumb');
            if ($info)
            {
                if ($info['status'])
                {
                    if (!empty($articleInfo['thumb']))
                    {
                        $path          = './public/'.$articleInfo['thumb'];
                        if (file_exists($path))
                        {
                            @unlink($path);
                        }
                    }
                    $data['thumb'] = $info['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info['msg']];
                }
            } else {
                if (isset($data['thumb_del']))
                {
                    $data['thumb'] = null;
                } else {
                    $data['thumb'] = $articleInfo['thumb'];
                }
            }
            $info2   = muti_img_upload('photos');
            if ($info2)
            {
                if ($info2['status'])
                {
                    if (!empty($articleInfo['photos']))
                    {
                        foreach ($articleInfo['photos'] as $val) {
                            $path          = './public/'.$val['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    $data['photos'] = $info2['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info2['msg']];
                }
            } else {
                if (isset($data['photos_del']))
                {
                    if (!empty($articleInfo['photos']))
                    {
                        foreach ($articleInfo['photos'] as $val) {
                            $path          = './public/'.$val['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    $data['photos'] = null;
                } else {
                    $data['photos'] = $articleInfo['photos'];
                }
            }
            $info3   = muti_soft_upload('enclosure');
            if ($info3)
            {
                if ($info3['status'])
                {
                    if (!empty($articleInfo['enclosure']))
                    {
                        foreach ($articleInfo['enclosure'] as $value) {
                            $path = './public/'.$value['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    $data['enclosure'] = $info3['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info3['msg']];
                }
            } else {
                if (isset($data['enclosure_del']))
                {
                    if (!empty($articleInfo['enclosure']))
                    {
                        foreach ($articleInfo['enclosure'] as $value) {
                            $path = './public/'.$value['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    $data['enclosure'] = null;
                } else {
                    $data['enclosure'] = $articleInfo['enclosure'];
                }
            }
            $system = Loader::model('Article');
            $system->edit($data);
            return ['status'=>true, 'msg'=>$data];
        }
    }

    /**
     * 文章删除
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (request()->isPost())
        {
            $chk = check_juri(request()->controller(), 'del', $this->_juri);
            if ($chk['status'])
            {
                $id = intval(input('param.id'));
                $res = Db::name('article')->where('id', $id)->update(['del_status'=>1]);
                if ($res)
                {
                    return ['status'=>true, 'msg'=>'删除成功'];
                } else {
                    return ['status'=>false, 'msg'=>'删除失败'];
                }
            } else {
                return ['status'=>false, 'msg'=>$chk['msg']];
            }
        }
    }



    public function recycle()
    {
        $chk = check_juri(request()->controller(), 'recycle', $this->_juri);
        if ($chk['status'])
        {
            $where = 'a.del_status = 1';
            $data['title']  = '';
            $data['cid']    = 0;
            $data['status'] = 'all';
            $date_start     = time();
            $date_end       = $date_start;
            if (Request::instance()->isGet())
            {
                $request = Request::instance()->param();
                if ($request)
                {
                    $data = $request;
                    if (isset($data['title']) && !empty($data['title']))
                    {
                        $where .= ' and CONCAT_WS(",", a.title, a.author, a.keywords, a.description) like "%'.$data['title'].'%"';
                    } else {
                        $data['title']  = '';
                    }

                    if (isset($data['cid']) && !empty($data['cid']))
                    {
                        $where .= ' and a.category_id = '.$data['cid'];
                    } else {
                        $data['cid']    = 0;
                    }

                    if (isset($data['status']) && $data['status'] != 'all')
                    {
                        $where .= ' and a.status = '.$data['status'];
                    } else {
                        $data['status'] = 'all';
                    }
                    if (isset($data['daterange']) && !empty($data['daterange']))
                    {
                        $date_arr   = explode('-', $data['daterange']);
                        $date_start = strtotime(trim($date_arr[0]));
                        $date_end   = strtotime(trim($date_arr[1]));
                        if (($date_end-$date_start) > 0)
                        {
                            $where .= ' and a.create_time between '.$date_start.' and '.$date_end;
                        }
                    }
                }
            }
            $total = Loader::model('Article')
                ->alias('a')
                ->where($where)
                ->count();
            $list = Loader::model('Article')
                ->alias('a')
                ->field('a.id, a.thumb, a.title, a.other_title, a.category_id, a.author, a.hits, a.attr, a.is_top, a.create_time, a.update_time, a.status, a.url_post, c.title as category_name')
                ->join('__CATEGORY__ c', 'a.category_id = c.id', 'LEFT')
                ->where($where)
                ->order('a.sort desc, a.create_time desc')
                ->paginate(30, $total, ['query'=>['title'=>$data['title'], 'cid'=>$data['cid'], 'status'=>$data['status'], 'daterange'=>date('Y/m/d', $date_start).' - '.date('Y/m/d', $date_end)]]);
            $pages = $list->render();
            $cate = Db::name('category')
                ->field('id, title, parentid, attr')
                ->order('sort desc, create_time desc')
                ->select();
            $tree = new Tree($cate);
            $cate = $tree->get_tree(0);
            return view('recycle', [
                'list'      =>$list,
                'cate'      =>$cate,
                'pages'     =>$pages,
                'data'      =>$data,
                'date_start'=>$date_start,
                'date_end'  =>$date_end
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    public function recovery()
    {
        if (request()->isPost())
        {
            $chk = check_juri(request()->controller(), 'recovery', $this->_juri);
            if ($chk['status'])
            {
                $id = intval(input('param.id'));
                $res = Db::name('article')->where('id', $id)->update(['del_status'=>0]);
                if ($res)
                {
                    return ['status'=>true, 'msg'=>'恢复成功'];
                } else {
                    return ['status'=>false, 'msg'=>'恢复失败'];
                }
            } else {
                return ['status'=>false, 'msg'=>$chk['msg']];
            }
        }
    }

    public function thoroughDel()
    {
        if (request()->isPost())
        {
            $chk = check_juri(request()->controller(), 'thoroughDel', $this->_juri);
            if ($chk['status'])
            {
                $id   = intval(input('param.id'));
                $info = Loader::model('Article')->get($id);
                $res  = Db::name('article')->where('id', $id)->delete();
                if ($res)
                {
                    if (!empty($info['thumb']))
                    {
                        $path          = './public/'.$info['thumb'];
                        if (file_exists($path))
                        {
                            @unlink($path);
                        }
                    }
                    if (!empty($info['photos']))
                    {
                        foreach ($info['photos'] as $val) {
                            $path          = './public/'.$val['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    if (!empty($info['enclosure']))
                    {
                        foreach ($info['enclosure'] as $val) {
                            $path          = './public/'.$val['path'];
                            if (file_exists($path))
                            {
                                @unlink($path);
                            }
                        }
                    }
                    return ['status'=>true, 'msg'=>'删除成功'];
                } else {
                    return ['status'=>false, 'msg'=>'删除失败'];
                }
            } else {
                return ['status'=>false, 'msg'=>$chk['msg']];
            }
        }
    }

    public function urlPost()
    {
        if (request()->isPost())
        {
            $chk = check_juri(request()->controller(), 'urlPost', $this->_juri);
            if ($chk['status'])
            {
                $id    = intval(input('param.id'));
                $token = config('baidu_post_token');
                if ($token)
                {
                    $urls      = [];
                    $urlPc     = url('home/article/index', ['id'=>$id]);
                    array_push($urls, $urlPc);
                    if (config('mobile_status'))
                    {
                        $urlMobile = url('mobile/article/index', ['id'=>$id]);
                        array_push($urls, $urlMobile);
                    }
                    $api = 'http://data.zz.baidu.com/urls?site='.config('site_domain').'&token='.config('baidu_post_token');
                    $ch = curl_init();
                    $options =  array(
                        CURLOPT_URL => $api,
                        CURLOPT_POST => true,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_POSTFIELDS => implode("\n", $urls),
                        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
                    );
                    curl_setopt_array($ch, $options);
                    $result = curl_exec($ch);
                    if ($result)
                    {
                        Db::name('article')->where('id', $id)->update(['url_post'=>1]);
                        return ['status'=>true, 'msg'=>'推送成功'];
                    } else {
                        return ['status'=>false, 'msg'=>'推送失败'];
                    }
                } else {
                    return ['status'=>false, 'msg'=>'百度推送token未定义'];
                }
            } else {
                return ['status'=>false, 'msg'=>$chk['msg']];
            }
        }
    }
}